package com.kws.payment.service.impl;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.chinaums.open.api.OpenApiCache;
import com.chinaums.open.api.OpenApiContext;
import com.chinaums.open.api.constants.ConfigBean;
import com.chinaums.open.api.internal.util.http.HttpTransport;
import com.google.gson.JsonObject;
import com.kws.common.core.domain.R;
import com.kws.common.core.utils.StringUtils;
import com.kws.payment.dao.*;
import com.kws.payment.dao.info.CancelUnionPayOrderInfo;
import com.kws.payment.dao.info.RefundUnionPayOrderInfo;
import com.kws.payment.service.UnionPayService;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.UUID;

/**
 * <b>UnionPayServiceImpl</b>
 *
 * @description: UnionPayServiceImpl <br>
 * @date: 2024/11/27 16:55 <br>
 * @author: lhm <br>
 * @version: 1.0 <br>
 */

@Service
public class UnionPayServiceImpl implements UnionPayService {
    private static final Logger logger = LoggerFactory.getLogger(UnionPayServiceImpl.class);

    /**
     * 银联分配appId
     */
    public String appId = "10037e6f6a4e6da4016a670fd4530012";

    /**
     * 银联分配appkey
     */
    public String appKey = "f7a74b6c02ae4e1e94aaba311c04acf2";

    /**
     * 银联支付宝H5支付地址
     */
    public String alipayUrl = "https://api-mop.chinaums.com/v1/netpay/trade/h5-pay";

    /**
     * 银联微信H5支付地址
     */

    public String weixinpayUrl = "https://api-mop.chinaums.com/v1/netpay/wxpay/h5-to-minipay";

    /**
     * 银联云闪付H5支付地址
     */

    public String unionPayUrl = "https://api-mop.chinaums.com/v1/netpay/uac/order";

    /**
     * 银联退款地址
     */

    public String refundUrl = "https://api-mop.chinaums.com/v1/netpay/refund";

    /**
     * 银联取消订单地址
     */
    public String cancelOrderUrl = "https://api-mop.chinaums.com/v1/netpay/close";

    /**
     * 支付回调地址
     */
    public String notifyUrl = "";

    /**
     * 支付结果回跳商户页面地址
     */
    public String returnUrl = "";


    /**
     * 银联分配商户ID
     */
    public String mid = "898201612345678";

    /**
     * 银联分配商户终端号
     */
    public String tid = "88880001";


    @Override
    public R aliPayCreateOrder(UnionPayRq rq) throws Exception {
        UnionPayH5Rq unionPayH5Rq = new UnionPayH5Rq();
        unionPayH5Rq.setRequestTimestamp(DateUtil.format(new Date(), DatePattern.NORM_DATETIME_FORMATTER));
        unionPayH5Rq.setMid(mid);
        unionPayH5Rq.setTid(tid);
        unionPayH5Rq.setInstMid("APPDEFAULT");
        unionPayH5Rq.setMerOrderId(rq.getOrderNo());
        unionPayH5Rq.setNotifyUrl(notifyUrl);
        unionPayH5Rq.setReturnUrl(returnUrl);
        unionPayH5Rq.setLimitCreditCard("false");
        unionPayH5Rq.setDivisionFlag(true);
        unionPayH5Rq.setPlatformAmount(0);
        ConfigBean configBean = new ConfigBean();
        OpenApiContext context = new OpenApiContext();
        context.setApiServiceUrl(alipayUrl);
        context.setAppId(appId);
        context.setAppKey(appKey);
        context.setConfigBean(configBean);
        String str = HttpTransport.getInstance().doGet(context, JSONUtil.toJsonStr(JSONUtil.parse(unionPayH5Rq)));
        logger.info("获取银联支付宝下单返回结果:"+str);
        return R.ok(str);
    }

    @Override
    public R weixinPayCreateOrder(UnionPayRq rq) {
        UnionPayH5Rq unionPayH5Rq = new UnionPayH5Rq();
        unionPayH5Rq.setRequestTimestamp(DateUtil.format(new Date(), DatePattern.NORM_DATETIME_FORMATTER));
        unionPayH5Rq.setMid(mid);
        unionPayH5Rq.setTid(tid);
        unionPayH5Rq.setInstMid("APPDEFAULT");
        unionPayH5Rq.setMerOrderId(rq.getOrderNo());
        unionPayH5Rq.setNotifyUrl(notifyUrl);
        unionPayH5Rq.setReturnUrl(returnUrl);
        unionPayH5Rq.setLimitCreditCard("false");
        unionPayH5Rq.setDivisionFlag(true);
        unionPayH5Rq.setPlatformAmount(0);
        ConfigBean configBean = new ConfigBean();
        OpenApiContext context = new OpenApiContext();
        context.setApiServiceUrl(weixinpayUrl);
        context.setAppId(appId);
        context.setAppKey(appKey);
        context.setConfigBean(configBean);
        String str = HttpTransport.getInstance().doGet(context, JSONUtil.toJsonStr(JSONUtil.parse(unionPayH5Rq)));
        logger.info("获取银联微信支付下单返回结果:"+str);
        return R.ok(str);
    }

    @Override
    public R unionPayCreateOrder(UnionPayRq rq) {
        UnionPayH5Rq unionPayH5Rq = new UnionPayH5Rq();
        unionPayH5Rq.setRequestTimestamp(DateUtil.format(new Date(), DatePattern.NORM_DATETIME_FORMATTER));
        unionPayH5Rq.setMid(mid);
        unionPayH5Rq.setTid(tid);
        unionPayH5Rq.setInstMid("APPDEFAULT");
        unionPayH5Rq.setMerOrderId(rq.getOrderNo());
        unionPayH5Rq.setNotifyUrl(notifyUrl);
        unionPayH5Rq.setReturnUrl(returnUrl);
        unionPayH5Rq.setLimitCreditCard("false");
        unionPayH5Rq.setDivisionFlag(true);
        unionPayH5Rq.setPlatformAmount(0);
        ConfigBean configBean = new ConfigBean();
        OpenApiContext context = new OpenApiContext();
        context.setApiServiceUrl(unionPayUrl);
        context.setAppId(appId);
        context.setAppKey(appKey);
        context.setConfigBean(configBean);
        String str = HttpTransport.getInstance().doGet(context, JSONUtil.toJsonStr(JSONUtil.parse(unionPayH5Rq)));
        logger.info("获取银联微信支付下单返回结果:"+str);
        return R.ok(str);
    }

    @Override
    public R refundOrder(RefundUnionPayRq rq) throws Exception {
        RefundUnionPayH5Rq refundUnionPayH5Rq = new RefundUnionPayH5Rq();
        refundUnionPayH5Rq.setRequestTimestamp(DateUtil.format(new Date(), DatePattern.NORM_DATETIME_FORMATTER));
        refundUnionPayH5Rq.setMerOrderId(rq.getOrderNo());
        refundUnionPayH5Rq.setInstMid("H5DEFAULT");
        refundUnionPayH5Rq.setMid(mid);
        refundUnionPayH5Rq.setTid(tid);
        refundUnionPayH5Rq.setRefundAmount(rq.getRefundAmount());
        refundUnionPayH5Rq.setRefundOrderId(rq.getRefundOrderId());
        ConfigBean configBean = new ConfigBean();
        OpenApiContext context = new OpenApiContext();
        context.setStartTime(System.currentTimeMillis());
        context.setRequestId(UUID.randomUUID().toString().replace("-", ""));
        context.setOpenServUrl(refundUrl.split("/v")[0].concat("/"));
        context.setApiServiceUrl(refundUrl);
        context.setVersion(refundUrl.split("/")[3]);
        context.setAppId(appId);
        context.setAppKey(appKey);
        context.setConfigBean(configBean);
        context.setServiceCode(refundUrl.split("/v")[1].substring(1));
        OpenApiCache.getCurrentToken(context);
        String str = HttpTransport.getInstance().doPost(context, JSONUtil.toJsonStr(JSONUtil.parse(refundUnionPayH5Rq)));
        logger.info("调用退款银联退款返回结果:"+str);
        if (StringUtils.isNotEmpty(str)){
            RefundUnionPayOrderInfo info = JSONUtil.toBean(str,RefundUnionPayOrderInfo.class);
            if ("SUCCESS".equals(info.getErrCode())){
                return R.ok(info);
            }else {
                return R.fail(info.getErrInfo());
            }
        }
        return null;
    }

    @Override
    public R cancelOrder(UnionPayRq rq) throws Exception {
        CancelUnionPayOrderRq cancelUnionPayOrderRq = new CancelUnionPayOrderRq();
        cancelUnionPayOrderRq.setRequestTimestamp(DateUtil.format(new Date(), DatePattern.NORM_DATETIME_FORMATTER));
        cancelUnionPayOrderRq.setMerOrderId(rq.getOrderNo());
        cancelUnionPayOrderRq.setInstMid("H5DEFAULT");
        cancelUnionPayOrderRq.setMid(mid);
        cancelUnionPayOrderRq.setTid(tid);

        ConfigBean configBean = new ConfigBean();
        OpenApiContext context = new OpenApiContext();
        context.setStartTime(System.currentTimeMillis());
        context.setRequestId(UUID.randomUUID().toString().replace("-", ""));
        context.setOpenServUrl(cancelOrderUrl.split("/v")[0].concat("/"));
        context.setApiServiceUrl(cancelOrderUrl);
        context.setVersion(cancelOrderUrl.split("/")[3]);
        context.setAppId(appId);
        context.setAppKey(appKey);
        context.setConfigBean(configBean);
        context.setServiceCode(cancelOrderUrl.split("/v")[1].substring(1));
        OpenApiCache.getCurrentToken(context);
        String str = HttpTransport.getInstance().doPost(context, JSONUtil.toJsonStr(JSONUtil.parse(cancelUnionPayOrderRq)));
        logger.info("调用银联接口取消支付订单返回结果:"+str);
        if (StringUtils.isNotEmpty(str)){
            CancelUnionPayOrderInfo info = JSONUtil.toBean(str, CancelUnionPayOrderInfo.class);
            if ("SUCCESS".equals(info.getErrCode())){
                return R.ok(info);
            }else {
                return R.fail(info.getErrMsg());
            }
        }
        return null;
    }

    @Override
    public JsonObject unionPayResultNotification(UnionPayResultNotificationRq rq) {
        JsonObject resultJson = new JsonObject();
        if (null != rq && "TRADE_SUCCESS".equals(rq.getStatus())){
            logger.info("支付成功");
            resultJson.addProperty("code","SUCCESS");
        }else {
            resultJson.addProperty("code","FAILED");
        }
        return resultJson;
    }

    @Override
    public JsonObject refundResultNotification(UnionPayResultNotificationRq rq) {
        JsonObject resultJson = new JsonObject();
        if (null != rq && "TRADE_SUCCESS".equals(rq.getStatus())){
            logger.info("支付成功");
            resultJson.addProperty("code","SUCCESS");
        }else {
            resultJson.addProperty("code","FAILED");
        }
        return resultJson;
    }
}
